﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.SessionState;

namespace LongSpeed.WebSite.Behaviors
{
    public class RequestHandle : IHttpModule, IRequiresSessionState
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += MyRequest;
        }
        public void Dispose()
        {

        }
        protected void MyRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            string path = app.Context.Request.Url.AbsoluteUri;
            var p = path.Split('/');
            path = p[p.Length - 1];

            switch (path)
            {
                case "home.htm":
                    HttpContext.Current.RewritePath("~/Default.aspx");
                    return;
                default:
                    break;
            }
            if (path != "")
            {
                path = app.Context.Request.Url.AbsolutePath.Replace("/", "");
                UrlMapping urlmapping = new UrlMapping();
                urlmapping = urlmapping.GetModel(path);
                if (urlmapping != null)
                {
                    string pageIndex = app.Context.Request.Url.Query.Replace("?", "");
                    if (!string.IsNullOrEmpty(pageIndex) && !string.IsNullOrWhiteSpace(pageIndex))
                    {
                        pageIndex = string.Format("&pageIndex={0}", pageIndex);
                    }
                    string url = string.Format("{0}?{1}{2}", urlmapping.ToAddress, urlmapping.Args, pageIndex);
                    HttpContext.Current.RewritePath(url);
                }
            }

            //新闻
            Regex newReg = new Regex(@"^new-(?<aid>\d+)-(?<apart>\d+).html$");
            //服务器（菜单）
            Regex serverReg = new Regex(@"^server-(?<pid>\d+).html$");
            //机房（菜单）
            Regex roomReg = new Regex(@"^room-(?<mid>\d+)-(?<pid>\d+).html");
            //服务器信息
            Regex serverInfoReg = new Regex(@"^serverinfo-(?<sid>\d+).html$");
            //文章
            Regex articleReg = new Regex(@"^article-(?<aid>\d+)-(?<pid>\d+).html$");
            //文章列表
            Regex articleListReg = new Regex(@"^articlelist-(?<pid>\d+).html$");
            //机房分页
            Regex roomPageReg = new Regex(@"^room-(?<mid>\d+)-(?<pid>\d+)-(?<pageIndex>\d+).html");
            //文章列表分页
            Regex articleListPageReg = new Regex(@"^articlelist-(?<pid>\d+)-(?<pageIndex>\d+).html$");

            var newMatch = newReg.Match(path);
            var serverMatch = serverReg.Match(path);
            var roomMatch = roomReg.Match(path);
            var serverInfoMatch = serverInfoReg.Match(path);
            var articleMatch = articleReg.Match(path);
            var articleListMatch = articleListReg.Match(path);
            var roomPageMatch = roomPageReg.Match(path);
            var articleListPageMatch = articleListPageReg.Match(path);

            if (newMatch.Success)
            {
                var aid = newMatch.Groups["aid"].Value;
                var apart = newMatch.Groups["apart"].Value;
                string url = string.Format("~/Main/Article.aspx?aid={0}&apart={1}", aid, apart);
                HttpContext.Current.RewritePath(url);
            }
            else if (serverMatch.Success)
            {
                var pid = serverMatch.Groups["pid"].Value;
                string url = string.Format("~/Main/RegionalServer.aspx?pid={0}", pid);
                HttpContext.Current.RewritePath(url);
            }
            else if (roomMatch.Success)
            {
                var mid = roomMatch.Groups["mid"].Value;
                var pid = roomMatch.Groups["pid"].Value;
                string url = string.Format("~/Main/EngineRoom.aspx?mid={0}&pid={1}", mid, pid);
                HttpContext.Current.RewritePath(url);
            }
            else if (serverInfoMatch.Success)
            {
                var sid = serverInfoMatch.Groups["sid"].Value;
                string url = string.Format("~/Main/SserverConfigInfo.aspx?sid={0}", sid);
                HttpContext.Current.RewritePath(url);
            }
            else if (articleMatch.Success)
            {
                var aid = articleMatch.Groups["aid"].Value;
                var apart = articleMatch.Groups["pid"].Value;
                string url = string.Format("~/Main/ArticleInfo.aspx?aid={0}&apart={1}", aid, apart);
                HttpContext.Current.RewritePath(url);
            }
            else if (articleListMatch.Success)
            {
                var pid = articleListMatch.Groups["pid"].Value;
                string url = string.Format("~/Main/ArticleListView.aspx?apart={0}", pid);
                HttpContext.Current.RewritePath(url);
            }
            else if (roomPageMatch.Success)
            {
                var mid = roomPageMatch.Groups["mid"].Value;
                var pid = roomPageMatch.Groups["pid"].Value;
                var pageIndex = roomPageMatch.Groups["pageIndex"].Value;
                string url = string.Format("~/Main/EngineRoom.aspx?mid={0}&pid={1}&pageIndex={2}", mid, pid, pageIndex);
                HttpContext.Current.RewritePath(url);
            }
            else if (articleListPageMatch.Success)
            {
                var pid = articleListPageMatch.Groups["pid"].Value;
                var pageIndex = articleListPageMatch.Groups["pageIndex"].Value;
                string url = string.Format("~/Main/ArticleListView.aspx?apart={0}&pageIndex={1}", pid, pageIndex);
                HttpContext.Current.RewritePath(url);
            }





            //string fname = System.IO.Path.GetFileNameWithoutExtension(path);
            //app.Context.Response.Write("请求开始……" + fname + "<br/>");
            //string[] str = fname.Split('-');
            //if (str.Length != 2)
            //{
            //    app.Context.Response.Write("请求的路径错误");
            //}
            //else
            //{
            //    ///url重写网址 //  app.Context.RewritePath
            //    app.Context.Response.Write("~/" + str[0] + ".aspx?id=" + str[1]);
            //}
            /////正则表达式匹配
            //Regex reg = new Regex("([A-Za-z1-9]{1,})\\-(\\d+).html");
            //Match match = reg.Match(fname);
            //if (match.Success)
            //{
            //    for (int i = 0; i < match.Groups.Count; i++)
            //        app.Context.Response.Write(match.Groups[i].Value + "<br/>");
            //    app.Context.Response.Write("~/" + match.Groups[1].Value + ".aspx?id=" + match.Groups[2].Value);
            //    ///             http://localhost:6685/Read-14562.html
            //    ///转换成实际的 http://localhost:6685/Read.aspx?id=14562
            //}
            //app.Context.RewritePath("~/Default.aspx");
        }
        ///网站项目中添加对该类库的引用
        ///Web.config文件中加入注册处理程序
        //<httpModules>
        //  <add name="MyModule" type="handle.Myhandle,handle"/>  ///加入这一句，handle为类库项目名，Myhandle为类名
        //  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        //</httpModules>
    }
}